package com.tanhua.dubbo.mongo.api;

import com.tanhua.model.mongo.ResultTable;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class ResultTableApiImpl  implements ResultTableApi{


    @Autowired
    private MongoTemplate mongoTemplate;

    //根据userId和问卷id查询数据库是否有数据
    public ResultTable findResult(Long userId, ObjectId testSoulId) {
        Criteria criteria = Criteria.where("testSoulId").is(testSoulId).and("userId").is(userId);
        Query query = Query.query(criteria);
        ResultTable one = mongoTemplate.findOne(query, ResultTable.class);
        return one;
    }

    //保存 并返回结果表id
    public String saveResult(ResultTable resultTable) {
        ResultTable table = mongoTemplate.save(resultTable);
        return table.getId().toString();
    }

    //更新表数据
    public String updateResult(ResultTable resultTable, int count, Integer type) {
        Query query = Query.query(Criteria.where("id").is(resultTable.getId()));
        Update update=new Update();
        update.set("score",count);
        update.set("type",type);
        mongoTemplate.updateFirst(query,update,ResultTable.class);
        return resultTable.getId().toString();
    }

    //根据类型查询结果表数据
    public List<ResultTable> findByType(Integer type) {
        Criteria criteria = Criteria.where("type").is(type);
        Query query = Query.query(criteria);
        List<ResultTable> resultTables = mongoTemplate.find(query, ResultTable.class);

        return resultTables;
    }

    //根据表Id查询结果数据
    public ResultTable findById(String id) {
        Criteria criteria = Criteria.where("id").is(id);
        Query query = Query.query(criteria);
        ResultTable one = mongoTemplate.findOne(query, ResultTable.class);
        return one;
    }

    //根据用户id查询所有结果
    public Map<ObjectId, ResultTable> findByUserId(Long userId) {

        Query query = Query.query(Criteria.where("userId").is(userId));
        List<ResultTable> resultTables = mongoTemplate.find(query, ResultTable.class);

        Map<ObjectId,ResultTable> map=new HashMap<>();

        for (ResultTable resultTable : resultTables) {

            map.put(resultTable.getTestSoulId(),resultTable);
        }
        return map;
    }
}
